package April._23.answer.work4;

import java.io.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Main {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<String> f1 = new FutureTask<>(new FileCopyCallableTask("fileTest\\a.txt", "fileTest\\acopy1.txt"));
        FutureTask<String> f2 = new FutureTask<>(new FileCopyCallableTask("fileTest\\a.txt", "fileTest\\acopy2.txt"));
        FutureTask<String> f3 = new FutureTask<>(new FileCopyCallableTask("fileTest\\a.txt", "fileTest\\acopy3.txt"));
        new Thread(f1, "线程A").start();
        new Thread(f2, "线程B").start();
        new Thread(f3, "线程C").start();

        String msg1 = f1.get();
        String msg2 = f2.get();
        String msg3 = f3.get();
        new Thread(() -> {
            PrintWriter out = null;
            try {
                out = new PrintWriter("fileTest\\time.txt");
                out.println(msg1);
                out.println(msg2);
                out.println(msg3);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }finally {
                if (out != null){
                    out.close();
                }
            }
        }).start();
    }
}

class FileCopyCallableTask implements Callable<String> {
    private String srcFile;
    private String dstFile;

    public FileCopyCallableTask(String srcFile, String dstFile) {
        this.srcFile = srcFile;
        this.dstFile = dstFile;
    }

    @Override
    public String call() throws Exception {
        long time1 = System.currentTimeMillis();
        long srcLength = new File(srcFile).length();
        try (FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(dstFile)) {
            int readData;
            int len = 0;
            while ((readData = in.read()) != -1) {
                out.write(readData);
                len++;
                String percent = String.format("%.2f", ((len * 1.0) / srcLength) * 100);
                System.out.println(Thread.currentThread().getName() + "已复制了" + percent + "%");
            }
        }
        long time2 = System.currentTimeMillis();
        return Thread.currentThread().getName() + "花费了" + (time2 - time1) + "毫秒的时间完成了复制!";
    }
}
